package cn.mengfly.testnrz.im.client.handler;

import cn.mengfly.testnrz.im.ProtoMsg;
import cn.mengfly.testnrz.im.client.ClientSession;
import cn.mengfly.testnrz.im.client.ProtoInstant;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author Mengfly
 */
@ChannelHandler.Sharable
public class LoginResponseHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }
        // 判断消息类型
        ProtoMsg.Message pkg = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType headType = pkg.getType();
        if (!headType.equals(ProtoMsg.HeadType.LOGIN_RESPONSE)) {
            super.channelRead(ctx, msg);
            return;
        }
        ProtoMsg.LoginResponse info = pkg.getLoginResponse();
        ProtoInstant.ResultCodeEnum result = ProtoInstant.ResultCodeEnum.values()[info.getCode()];
        if (!result.equals(ProtoInstant.ResultCodeEnum.SUCCESS)) {
            // 登录失败
            System.out.println(result.getDesc());
        } else {
            ClientSession.loginSuccess(ctx, pkg);
            // 移除登录处理器
            ctx.pipeline().remove(this);
            // 在编码器后面，动态添加心跳处理器
            ctx.pipeline().addAfter("encoder", "heartbeat", new HeartBeatClientHandler());
        }
    }
}
